package controller

import (
	"github.com/gin-gonic/gin"
	"myserver/model"
	"myserver/param"
	"myserver/response"
	"myserver/service"
)

type FamilyController struct {
}

var familyService = service.FamilyService{}

func (c *FamilyController) Router(apiGroup *gin.RouterGroup) {
	apiGroup.GET("/family", c.gets)
	apiGroup.POST("/family", c.posts)
	apiGroup.DELETE("/family", c.deletes)
	apiGroup.PUT("/family", c.puts)

	apiGroup.GET("/families", c.getPage)
}

func (c *FamilyController) gets(context *gin.Context) {
	id, b := context.GetQuery("ID")
	if !b {
		response.Failed(context, response.Error())
	}
	family := familyService.GetFamily(id)
	if family.ID != 0 {
		response.Success(context, response.Ok().AddData("family", family))
	} else {
		response.Failed(context, response.Error())
	}
}
func (c *FamilyController) getPage(context *gin.Context) {
	var pageParam param.PageParam
	err := context.ShouldBind(&pageParam)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := familyService.GetFamilyPage(pageParam)
	if res.Data != nil && res.Total != 0 {
		response.Success(context, response.Ok().AddData("res", res))
	} else {
		response.Failed(context, response.Ok().AddData("res", res))
	}
}

func (c *FamilyController) posts(context *gin.Context) {
	var family model.Family
	err := context.ShouldBind(&family)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := familyService.CreateFamily(family)
	if res != 0 {
		response.Success(context, response.Ok().AddData("res", res))
	} else {
		response.Failed(context, response.Error())
	}
}

func (c *FamilyController) deletes(context *gin.Context) {
	var family model.Family
	err := context.ShouldBind(&family)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := familyService.DeleteFamily(family)
	if res != 0 {
		response.Success(context, response.Ok().AddData("res", res))
	} else {
		response.Failed(context, response.Error())
	}
}

func (c *FamilyController) puts(context *gin.Context) {
	var family model.Family
	err := context.ShouldBind(&family)
	if err != nil {
		response.Failed(context, response.Error().AddData("msg", "参数解析失败"))
	}
	res := familyService.UpdateFamily(family)
	if res != 0 {
		response.Success(context, response.Ok().AddData("res", res))
	} else {
		response.Failed(context, response.Error())
	}
}
